package rpcbiz

import (
	"net"
	"fmt"
	"github.com/golang/glog"
	"cloud_worm/util/proto/urpc"
	"cloud_worm/util/unet/rpc"
	"cloud_worm/util/uconst"
	"cloud_worm/access/server/client"
	"cloud_worm/util/proto/ujson"
)


// --------------------- 配置更新的下发通知 ---------------------
type AutoConfigArgs urpc.AutoConfigArgs

func (args *AutoConfigArgs) param() error {
	if net.ParseIP(args.AgentIP) == nil {
		return fmt.Errorf("agent ip error")
	}
	if len(args.AgentID) < uconst.AgentIdLen {
		return fmt.Errorf("agent id error")
	}
	return nil
}

func (a *AutoConfig) DealAutoConfig(args *AutoConfigArgs, reply *urpc.AutoConfigReply) error {
	if err := args.param(); err != nil {
		return err
	}

	if client.AgentPoolInst.HaveConnByID(args.AgentID) == false {
		glog.Errorf("'%s' offline", args.AgentIP)
		return fmt.Errorf("agent '%s' offline", args.AgentIP)
	}

	autoConfReq := ujson.MsgAutoConfigReq{
		Id: args.AgentID,
		IP: args.AgentIP,
		NotifyType: args.NotifyType,
		PayLoad: args.PayLoad,
	}
	payLoad, _ := autoConfReq.MarshalJSON()
	sendMsg := ujson.ProtoMsg{Type: ujson.ProtoAutoConfigReq, Content: payLoad}
	sendBuf, err := sendMsg.MarshalJSON()
	if err != nil {
		glog.Errorf("proto msg marshal error")
		return err
	}

	agent := client.AgentPoolInst.GetAgentByID(args.AgentID)
	err = agent.Connection.Write(sendBuf)
	if err != nil {
		glog.Errorf("send msg to'%s' error: %s", args.AgentIP, err.Error())
		client.AgentPoolInst.DelAgent(agent)
		return fmt.Errorf("send auto config msg error")
	}

	// 仅关注到下发成功
	return nil
}

type AutoConfig int

func init()  {
	rpc.Register(new(AutoConfig))
}
